<template>
  <view class="pages">
    <nav-bar title='个人中心' titleSize='14' :backBtn='false'></nav-bar>
    <scroll-view class="user " scroll-y>
      <view class="padding-t20"></view>
      <cell-list>
        <cell-item title="头像" titleColor="#000" height="72px" borderBottom rightIcon @tap='chooseImage'>
          <image style="width: 62px;height: 62px;display: block;border-radius: 50%;" :src="user.head_pic || ossDomain + '/addressBook-edit-avatar.png'"></image>
        </cell-item>
        <cell-item title="姓名" titleColor="#000" :rightValue='user.username || ""' height="43px" borderBottom rightIcon></cell-item>
        <picker :range="sexList" :value="user.sex ? user.sex - 1 : user.sex" @change='changeSex'>
          <cell-item title="性别" titleColor="#000" :rightValue='sexList2[user.sex]' height="43px" borderBottom rightIcon></cell-item>
        </picker>
        <picker mode="date" @change="changeBirthday">
          <cell-item title="年龄" titleColor="#000" :rightValue='age' height="43px" borderBottom rightIcon></cell-item>
        </picker>
        <cell-item title="健康档案" titleColor="#000" height="43px" borderBottom rightIcon @tap="$navigateTo('/pages/daily-index/index')"></cell-item>
        <cell-item title="地址管理" titleColor="#000" height="43px" :borderBottom='false' rightIcon @tap="$navigateTo('/pages/address/list')"></cell-item>
      </cell-list>
      <view class="padding-t20"></view>
      <view class="user-reserve jh-flex-center" @tap="$navigateTo('/pages/user/reserve')">
        <image class='user-reserve-bg' :src="ossDomain + '/addressBook-item-bg.png'" mode="scaleToFill"></image>
        <view class="user-reserve-text font-B font-14">
          我的预约
        </view>
      </view>
      <view class="padding-t20 padding-b20"></view>
    </scroll-view>
  </view>
</template>

<script>
  import cellItem from '@/components/cell/item.vue'
  import cellList from '@/components/cell/list.vue'
  import {
    mapState
  } from 'vuex'
  export default {
    components: {
      cellItem,
      cellList
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
      }),
    },
    data() {
      return {
        ossDomain: uni.ossDomain,
        user: {},
        sexList: [
          '男',
          '女'
        ],
        sexList2: [
          '未知',
          '男',
          '女'
        ],
        age: '未知'
      }
    },
    watch: {
      user (e) {
        if (e.birthday) {
          this.age = this.getAge(e.birthday) || '未知'
        }
      }
    },
    mounted() {
      this.user = this.userInfo.user
      this.getInfo()
    },
    methods: {
      getInfo() {
        this.$http.getInfo().then(res => {
          let data = res.data
          this.userInfo.user = Object.assign(this.userInfo.user, data)
          this.$store.commit('setUserInfo', this.userInfo);
          this.user = this.userInfo.user
        })
      },
      changeSex(e) {
        console.log(e.detail.value);
        let obj = {
          sex: e.detail.value + 1
        }
        this.$http.updateInfo(obj).then(res => {
          this.userInfo.user.sex = obj.sex
          this.$store.commit('setUserInfo', this.userInfo);
          this.user = this.userInfo.user
        })
      },
      changeBirthday(e) {
        console.log(e.detail.value);
        let obj = {
          birthday: e.detail.value
        }
        this.$http.updateInfo(obj).then(res => {
          this.userInfo.user.birthday = e.detail.value
          this.$store.commit('setUserInfo', this.userInfo);
          this.user = this.userInfo.user
          this.age = this.getAge(obj.birthday) || '未知'
        })
      },
      getAge(str) {
        var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})/);
        if (r == null) return false;

        var d = new Date(r[1], r[3] - 1, r[4]);
        var returnStr = "输入的日期格式错误！";

        if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {

          var date = new Date();
          var yearNow = date.getFullYear();
          var monthNow = date.getMonth() + 1;
          var dayNow = date.getDate();

          var largeMonths = [1, 3, 5, 7, 8, 10, 12], //大月， 用于计算天，只在年月都为零时，天数有效
            lastMonth = monthNow - 1 > 0 ? monthNow - 1 : 12, // 上一个月的月份
            isLeapYear = false, // 是否是闰年
            daysOFMonth = 0; // 当前日期的上一个月多少天

          if ((yearNow % 4 === 0 && yearNow % 100 !== 0) || yearNow % 400 === 0) { // 是否闰年， 用于计算天，只在年月都为零时，天数有效
            isLeapYear = true;
          }

          if (largeMonths.indexOf(lastMonth) > -1) {
            daysOFMonth = 31;
          } else if (lastMonth === 2) {
            if (isLeapYear) {
              daysOFMonth = 29;
            } else {
              daysOFMonth = 28;
            }
          } else {
            daysOFMonth = 30;
          }

          var Y = yearNow - parseInt(r[1]);
          var M = monthNow - parseInt(r[3]);
          var D = dayNow - parseInt(r[4]);
          if (D < 0) {
            D = D + daysOFMonth; //借一个月
            M--;
          }
          if (M < 0) { // 借一年 12个月
            Y--;
            M = M + 12; //
          }

          if (Y < 0) {
            returnStr = "未知";
          } else if (Y === 0) {
            returnStr = '0岁'
            // if (M === 0) {
            //   returnStr = D + "日";
            // } else {
            //   returnStr = M + "月";
            // }
          } else {
            returnStr = Y + "岁";
            // if (M === 0) {
            //   returnStr = Y + "岁";
            // } else {
            //   returnStr = Y + "岁" + M + "月";
            // }
          }

        }
        return returnStr;
      },
      chooseImage () {
        uni.chooseImage({
          count:1,
          success: (e) => {
            this.changAvatar(e.tempFilePaths[0])
          }
        })
      },
      changAvatar (e) {
        this.$http.getUploadToken().then(res => {
          let data = res.data.token
          uni.$uploadUrl = {
            key: data.dir+(new Date()).getTime()+'.png',
            token: data.token,
            url: data.upload_url.upload_url
          }
          let {key, token, url} = uni.$uploadUrl
          uni.uploadFile({
            url: url,
            filePath: e,
            header: {
              appType: '3',
              version: this.version,
              sm: '',
              KaToken: uni.getStorageSync('KaToken')
            },
            name: 'file',
            formData: {
              key,
              token,
            },
            success: res => {
              uni.hideLoading()
              try {
                let _data = JSON.parse(res.data);
                _data = _data.data[0]
                uni.$navigateTo('/pages/cropper-default/cropper-default?src=http://'+ _data.url)
              } catch (e) {
                uni.showToast({
                  title: '上传失败'
                })
              }
            },
            fail: err => {
              uni.hideLoading()
            }
          });
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pages {
    width: 100%;
    height: 100vh;
    padding-right: 30px;
  }

  .user {
    padding-left: 30px;
    width: 100%;
    height: calc(100vh - 50px);
    box-sizing: border-box;

    &-avatar {
      width: 168px;
      height: 168px;
      background-color: #fff;
      border-radius: 50%;
    }

    &-reserve {
      width: 100%;
      height: 43px;
      border: 1px solid #ddd;
      position: relative;
      border-radius: 6px;
      overflow: hidden;

      &-bg {
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 1;
      }

      &-text {
        position: relative;
        z-index: 2;
        color: #231815
      }
    }
  }
</style>
